package com.xinchuang.utils;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2024/3/20 9:27
 */
public class OfficeUtil {


    public static void main(String[] args) {
        List<List<Double>> lists = csvFile("D:\\project\\temp\\20171209\\mch_points.csv");
        for (List<Double> list : lists) {
            System.out.println(list);
        }
    }

    public static List<List<Double>> csvFile(String fileUrl) {
        List resultList = new ArrayList<>();
        try {
            File file = FileUtil.newFile(fileUrl);
            if (file.isFile()) {
                List<Map<String, String>> maps = readCsv(fileUrl);
                int size = maps.size();
                int middle = maps.size() > 1000 ? size / 800 : 1;
                List<Double> list;
                for (int i = 0; i < maps.size(); i += middle) {
                    Map<String, String> map =  maps.get(i);
                    list = new ArrayList<>();
                    list.add(Double.valueOf(map.get(" X_coordinate reference image word")));
                    list.add(Double.valueOf(map.get(" Y_coordinate reference image word")));
                    list.add(0D);
                    resultList.add(list);
                }
                System.out.println(resultList.size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultList;
    }

    public static List<Map<String, String>> readCsv(String filePath) throws IOException {
        Reader in = new FileReader(filePath);
        try (Reader reader = new BufferedReader(in)) {
            // 创建CSVFormat实例，指定第一行为表头
            CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader();

            // 解析CSV文件
            CSVParser parser = new CSVParser(reader, csvFormat);

            List<Map<String, String>> data = new ArrayList<>();
            for (CSVRecord record : parser) {
                Map<String, String> row = new HashMap<>();
                // 遍历记录的所有字段
                for (String header : parser.getHeaderNames()) {
                    row.put(header, record.get(header));
                }
                data.add(row);
            }
            return data;
        }
    }

}
